import history from '@helpers/history'
import { storage } from '@helpers/storage'
import { Icon, Layout } from 'antd'
import * as React from 'react'
import { hot } from 'react-hot-loader'
import { Redirect, Route, Router, Switch, withRouter } from 'react-router-dom'
import { RouteConfigInter, routeConfigs } from 'routers/route'
import { AsideMenuComponent, ErrorComponent, LoginComponent } from 'routeTables'
import * as styles from './index.less'

const { Header: AntdHeader, Footer, Sider, Content } = Layout

const createRoute = (route: RouteConfigInter, index: number) => {
  return (
    <Route key={index} exact path={route.path} component={route.component} />
  )
}

const AuthWrap = withRouter((props: any) => {
  const { token } = storage.get(['token'])
  const url = `/login?target_url=${props.match.url}`
  if (!token) {
    props.history.replace(url)
  }
  return (props.children)
})

// tslint:disable-next-line:no-empty-interface
export interface IndexProps { }

class Index extends React.PureComponent<IndexProps, {}> {

  public render() {
    return (
      <Router history={history}>
        <Switch>
          <Route exact path='/404' component={ErrorComponent} />
          <Route exact path='/login' component={LoginComponent} />
          <Route exact path='/logout' component={LoginComponent} />
          <AuthWrap>
            <Layout>
              <Sider trigger={null} collapsible>
                <h1 className={styles.h2}>舞蹈学校管理后台</h1>
                <AsideMenuComponent />
              </Sider>
              <Layout>
                <AntdHeader style={{ background: '#fff', padding: 0 }}>
                  <Icon
                    className='trigger'
                    type='menu-unfold'
                  />
                </AntdHeader>
                <Content
                  style={{
                    margin: '24px 16px',
                    padding: 24,
                    background: '#fff',
                    minHeight: 'unset',
                  }}
                >
                  <Switch>
                    {routeConfigs.map((route, i) => createRoute(route, i))}
                    <Redirect to={{ pathname: '/404' }} />
                  </Switch>
                </Content>
                <Footer>Footer</Footer>
              </Layout>
              {/* <DevTools /> */}
            </Layout>
          </AuthWrap>
        </Switch>
      </Router>
    )
  }
}

export default hot(module)(Index)
